class SpringMulti extends egret.Sprite {
    private ball: Ball
    private handles: Array<Ball>
    private numHandles: number = 4
    private spring: number = 0.10
    private friction: number = 0.8

    private movingHandle: Ball = null

    public constructor() {
        super()
        this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(event: egret.Event) {
        this.ball = new Ball(20)
        this.addChild(this.ball)

        this.handles = new Array<Ball>()
        for (let i = 0; i < this.numHandles; ++i) {
            let handle = new Ball(10, 0x0000ff)
            handle.x = Math.random() * this.stage.stageWidth
            handle.y = Math.random() * this.stage.stageHeight
            handle.touchEnabled = true
            this.addChild(handle)
            this.handles.push(handle)
        }

        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchStart, this)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event: egret.Event) {
        for (let handle of this.handles) {
            this.ball.vx += (handle.x - this.ball.x) * this.spring
            this.ball.vy += (handle.y - this.ball.y) * this.spring
        }
        this.ball.vx *= this.friction
        this.ball.vy *= this.friction
        this.ball.x += this.ball.vx
        this.ball.y += this.ball.vy

        this.graphics.clear()
        this.graphics.lineStyle(1)
        for (let handle of this.handles) {
            this.graphics.moveTo(handle.x, handle.y)
            this.graphics.lineTo(this.ball.x, this.ball.y)
        }
    }

    private onTouchStart(evt: egret.TouchEvent) {
        if (evt.target instanceof Ball) {
            this.movingHandle = evt.target
        }
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this)
    }

    private onTouchEnd(evt: egret.TouchEvent) {
        this.movingHandle = null
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this)
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this)
    }

    private onTouchMove(evt: egret.TouchEvent) {
        if (this.movingHandle == null && evt.target instanceof Ball) {
            this.movingHandle = evt.target
        }

        if (this.movingHandle == null) {
            return
        }
        this.movingHandle.x = evt.stageX
        this.movingHandle.y = evt.stageY
    }
}